package GUI;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
import DAO.ProductDAO;
import DAO.ProductcatDAO;
import DAO.WarehouseDAO;
import GUI.Components.IToolbarPerformEvent;
import GUI.Components.JErrorProvider;
import GUI.Components.ToolbarEvent;
import POJO.*;
import Util.DataAccessUtil;
import Util.GuiUtil;
import Util.MsgUtil;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Nguyễn Thị Mỷ Diện (1142014)
 */
public class FrmWarehouse extends JInternalFrame {
    /**
     * Creates new form FrmWarehouse
     */
    private JErrorProvider jErrorControl;
    private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass().getName());

    public FrmWarehouse() {
        initComponents();
        jErrorControl = new JErrorProvider();
        toolbarWarehouse.setAllowEdit(false);
        tbDetailWarehouse.setModel(new DetailWarehouseTable(new ArrayList()));
        refreshControl(false);
        // Đăng ký sự kiện trên toolbar
        this.userControlForm();
    }
    /**
     * Lấy detail warehouse
     * @param warehouse 
     */
    private void loadDetailWarehouse(Warehouse warehouse) {
        List<Warehousedetail> listDetailWarehouse;
        try {
            listDetailWarehouse = WarehouseDAO.getListWarehouseDetails(warehouse.getId());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex.fillInStackTrace());
            return;
        }
        tbDetailWarehouse.setModel(new DetailWarehouseTable(listDetailWarehouse));
    }
    
    /**
     * Lấy model từ table detail warehouse
     * @return 
     */
    private DetailWarehouseTable getModelDetailWarehouse(){
        return (DetailWarehouseTable) tbDetailWarehouse.getModel();
    }
    
    //<editor-fold defaultstate="collapsed" desc="Refresh, cập nhập lại trạng thái controls">
    private void refreshControl(boolean editing){
        cboWarehouseId.setEditable(editing);
        btnAddDetailWarehouse.setEnabled(editing);
        btnRemoveDetailWarehouse.setEnabled(editing);
        cboProductType_DetailWarehouse.setEnabled(editing);
        cboProduct_DetailWarehouse.setEnabled(editing);
        txtQuantity_DetailWarehouse.setEnabled(editing);
        dateInput_DetailWarehouse.setEnabled(editing);
        
        if(editing){
            // reset combobox
            cboWarehouseId.setModel(new DefaultComboBoxModel());
            // set default date input
            dateInput_DetailWarehouse.setDate(new Date());
            // set customer name
            
            // prepare edit table
            List<Productcat> listProductCat = null;
            try {
                listProductCat = ProductcatDAO.getListProductCats(1);
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex.fillInStackTrace());
            }
            GuiUtil.addListCombobox(cboProductType_DetailWarehouse, listProductCat, "getName");
            // clear table
            getModelDetailWarehouse().removeAllElement();
        }else{
            // show model again
            List<Warehouse> listWarehouses;
            try {
                listWarehouses = WarehouseDAO.getListWarehouses();
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex.fillInStackTrace());
                return;
            }
            // Hiển thị lại cbo IDwarehouse
            GuiUtil.addListCombobox(cboWarehouseId, listWarehouses, "getId");
            // Xóa model trên các cbo
            cboProductType_DetailWarehouse.setModel(new DefaultComboBoxModel());
            cboProduct_DetailWarehouse.setModel(new DefaultComboBoxModel());
        }
    }
    //</editor-fold>

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel4 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JFormattedTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        dateInput_DetailWarehouse = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtNameEmployee = new javax.swing.JTextField();
        cboWarehouseId = new javax.swing.JComboBox();
        jPanelDetailWarehouse = new javax.swing.JPanel();
        btnAddDetailWarehouse = new javax.swing.JButton();
        btnRemoveDetailWarehouse = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDetailWarehouse = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        cboProductType_DetailWarehouse = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        cboProduct_DetailWarehouse = new javax.swing.JComboBox();
        txtQuantity_DetailWarehouse = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        toolbarWarehouse = new GUI.Components.Toolbar();

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1239, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 193, Short.MAX_VALUE)
        );

        jTabbedPane2.addTab("", jPanel4);

        jLabel3.setText("Tổng cộng:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 997, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(162, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jTabbedPane2.addTab("Lập phiếu nhập kho", jPanel2);

        setTitle("Nhập kho");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Phiếu nhập kho", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        jLabel5.setText("Ngày nhập:");
        jLabel5.setName("jLabel_idNgayXuatHD");

        jLabel2.setText("Nhân viên:");
        jLabel2.setName("jLabel_idNhanVien");

        jLabel1.setText("Phiếu nhập:");
        jLabel1.setName("jLabel_idHoaDon");

        txtNameEmployee.setEnabled(false);

        cboWarehouseId.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cboWarehouseIdItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtNameEmployee)
                    .addComponent(cboWarehouseId, 0, 180, Short.MAX_VALUE))
                .addGap(45, 45, 45)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(dateInput_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(82, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dateInput_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel5)
                            .addComponent(cboWarehouseId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtNameEmployee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanelDetailWarehouse.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Chi tiết phiếu nhập kho", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        btnAddDetailWarehouse.setText("Thêm");
        btnAddDetailWarehouse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddDetailWarehouseActionPerformed(evt);
            }
        });

        btnRemoveDetailWarehouse.setText("Xóa");
        btnRemoveDetailWarehouse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveDetailWarehouseActionPerformed(evt);
            }
        });

        tbDetailWarehouse.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Loại sản phẩm", "Sản phẩm", "Số lượng nhập"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbDetailWarehouse);
        tbDetailWarehouse.getColumnModel().getColumn(0).setResizable(false);
        tbDetailWarehouse.getColumnModel().getColumn(0).setPreferredWidth(350);
        tbDetailWarehouse.getColumnModel().getColumn(1).setResizable(false);
        tbDetailWarehouse.getColumnModel().getColumn(1).setPreferredWidth(350);
        tbDetailWarehouse.getColumnModel().getColumn(2).setResizable(false);
        tbDetailWarehouse.getColumnModel().getColumn(2).setPreferredWidth(150);

        jLabel4.setText("Loại sản phẩm:");
        jLabel4.setName("jLabel_idNhanVien");

        cboProductType_DetailWarehouse.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cboProductType_DetailWarehouseItemStateChanged(evt);
            }
        });

        jLabel6.setText("Tên sản phẩm:");
        jLabel6.setName("jLabel_idNhanVien");

        jLabel7.setText("Số lượng:");
        jLabel7.setName("jLabel_idNhanVien");

        javax.swing.GroupLayout jPanelDetailWarehouseLayout = new javax.swing.GroupLayout(jPanelDetailWarehouse);
        jPanelDetailWarehouse.setLayout(jPanelDetailWarehouseLayout);
        jPanelDetailWarehouseLayout.setHorizontalGroup(
            jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelDetailWarehouseLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelDetailWarehouseLayout.createSequentialGroup()
                        .addComponent(btnAddDetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemoveDetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanelDetailWarehouseLayout.createSequentialGroup()
                        .addGroup(jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(jPanelDetailWarehouseLayout.createSequentialGroup()
                                .addGroup(jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDetailWarehouseLayout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cboProductType_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanelDetailWarehouseLayout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cboProduct_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(1, 1, 1)))
                                .addGap(55, 55, 55)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtQuantity_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
        );
        jPanelDetailWarehouseLayout.setVerticalGroup(
            jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelDetailWarehouseLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cboProductType_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtQuantity_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(cboProduct_DetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelDetailWarehouseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddDetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnRemoveDetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanelDetailWarehouse, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolbarWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolbarWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelDetailWarehouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cboProductType_DetailWarehouseItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboProductType_DetailWarehouseItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            Productcat c = (Productcat) evt.getItem();
            try {
                List<Product> listProduct = ProductDAO.getListProducts(c.getId());
                GuiUtil.addListCombobox(cboProduct_DetailWarehouse, listProduct, "getName");
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex.fillInStackTrace());
            }
        }
    }//GEN-LAST:event_cboProductType_DetailWarehouseItemStateChanged

    private void btnRemoveDetailWarehouseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveDetailWarehouseActionPerformed
        getModelDetailWarehouse().removeElement(tbDetailWarehouse.getSelectedRow());
    }//GEN-LAST:event_btnRemoveDetailWarehouseActionPerformed

    private void btnAddDetailWarehouseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddDetailWarehouseActionPerformed
        jErrorControl.clear();
        int quantity;
        try {
            quantity = Integer.parseInt(txtQuantity_DetailWarehouse.getText());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex.fillInStackTrace());
            jErrorControl.setError(txtQuantity_DetailWarehouse,
                    "Số lượng không hợp lệ!");
            return;
        }
        Product product = (Product) cboProduct_DetailWarehouse.getSelectedItem();

        // Neu product co roi thi sua lai So luong quantity
        List<Warehousedetail> warehousedetails = getModelDetailWarehouse().getList();
        for (Warehousedetail wd : warehousedetails) {
            if (wd.getProduct().equals(product)) {
                wd.setTotal(wd.getTotal() + quantity);
                tbDetailWarehouse.updateUI(); // cập nhật lại table
                return;
            }
        }


        Warehousedetail wd = new Warehousedetail();
        wd.setProduct(product);
        wd.setTotal(quantity);
        getModelDetailWarehouse().addElement(wd);
    }//GEN-LAST:event_btnAddDetailWarehouseActionPerformed

    private void cboWarehouseIdItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboWarehouseIdItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (!(evt.getItem() instanceof Warehouse)) {
                // Clear table
                getModelDetailWarehouse().removeAllElement();
                return;
            }
            Warehouse w = (Warehouse) evt.getItem();
            dateInput_DetailWarehouse.setDate(w.getWarehousedate());
            txtNameEmployee.setText(w.getEmployee().getName());
            loadDetailWarehouse(w);
        }
    }//GEN-LAST:event_cboWarehouseIdItemStateChanged

        private void userControlForm(){
        toolbarWarehouse.addEventPerformClick(new IToolbarPerformEvent() {

            @Override
            public void performEventAdd(ToolbarEvent evt) {
                    refreshControl(true);
            }

            @Override
            public void performEventEdit(ToolbarEvent evt) {
                refreshControl(true);
            }

            @Override
            public void performEventDelete(ToolbarEvent evt) {
                if(cboWarehouseId.getSelectedItem() == null)
                    return;
                Warehouse w;
                try {
                     w  = (Warehouse) cboWarehouseId.getSelectedItem();
                } catch (Exception e) {
                    log.error(e.getMessage(),e.fillInStackTrace());
                    return;
                }
                if(MsgUtil.yesno("Bạn có muốn xóa phiếu: " +w.getId()+" hay không?")
                        == JOptionPane.YES_OPTION){
                    try {
                       // Set detail
                        w.setWarehousedetails(new HashSet(getModelDetailWarehouse().getList()));
                        // Delete
                        DataAccessUtil.delete(w);
                        MsgUtil.info("Xóa thành công!");
                        // Refresh controls
                        refreshControl(false);
                    } catch (Exception e) {
                         log.error(e.getMessage(),e.fillInStackTrace());
                         MsgUtil.error("Có lỗi trong quá trình xóa!",
                                 e.getMessage());
                    }
                }
                
            }

            @Override
            public void performEventSave(ToolbarEvent evt) {
                jErrorControl.clear();
                String code = cboWarehouseId.getSelectedItem().toString();
                if(code.isEmpty()){
                    jErrorControl.setError(cboWarehouseId, "Bạn chưa nhập mã phiếu");
                    evt.setIsError(true);
                    return;
                }
                try {
                    if(WarehouseDAO.checkExistsWarehouse(code)){
                        MsgUtil.error("Phiếu nhập \""+code+"\" đã tồn tại!");
                        evt.setIsError(true);
                        return;
                    }
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex.fillInStackTrace());
                    return;
                }
                
                Employee employee = new Employee();
                employee.setCode("NV001");
               
                Store store = new Store();
                store.setId(1);
                
                Warehouse warehouse = new Warehouse();
                warehouse.setId(code);
                warehouse.setEmployee(employee);
                warehouse.setStore(store);
                warehouse.setWarehousedate(dateInput_DetailWarehouse.getDate());
              
                for(Warehousedetail wd : getModelDetailWarehouse().getList()){
                    wd.setWarehouse(warehouse);
                    warehouse.getWarehousedetails().add(wd);
                }
                
                try {
                    DataAccessUtil.insert(warehouse);
                    MsgUtil.info("Lập phiếu thành công!");
                     refreshControl(false);
                } catch (Exception ex) {
                    log.error(ex.getMessage(),ex.fillInStackTrace());
                    MsgUtil.error("Có lỗi trong quá trình lập phiếu!",
                                 ex.getMessage() );
                }                
            }

            @Override
            public void performEventCancel(ToolbarEvent evt) {
                 refreshControl(false);
            }

            @Override
            public void performEventRefresh(ToolbarEvent evt) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void performEventClose(ToolbarEvent evt) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddDetailWarehouse;
    private javax.swing.JButton btnRemoveDetailWarehouse;
    private javax.swing.JComboBox cboProductType_DetailWarehouse;
    private javax.swing.JComboBox cboProduct_DetailWarehouse;
    private javax.swing.JComboBox cboWarehouseId;
    private com.toedter.calendar.JDateChooser dateInput_DetailWarehouse;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanelDetailWarehouse;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTable tbDetailWarehouse;
    private GUI.Components.Toolbar toolbarWarehouse;
    private javax.swing.JTextField txtNameEmployee;
    private javax.swing.JFormattedTextField txtQuantity_DetailWarehouse;
    private javax.swing.JFormattedTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}

//<editor-fold defaultstate="collapsed" desc="Detail warehouse  table">
class DetailWarehouseTable  extends AbstractTableModel{
    
    private static final String[] columnNames = {"Loại sản phẩm", "Sản phẩm", "Số lượng"};
    
    private List<Warehousedetail> list;
    
    public DetailWarehouseTable(List<Warehousedetail> list) {
        this.list = list;
    }
    
    public List<Warehousedetail> getList(){
        return this.list;
    }
    public void removeAllElement(){
        this.list.clear();
        fireTableDataChanged();
    }
    
    public void addElement(Warehousedetail e) {
        // Adds the element in the last position in the list
        list.add(e);
        fireTableRowsInserted(list.size()-1, list.size()-1);
    }
    public void removeElement(int rowIndex){
        list.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    }
    
    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }
    @Override
    public String getColumnName(int index){
       return columnNames[index];
    }
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex) {
            case 0: return list.get(rowIndex).getProduct().getProductcat().getName();
            case 1: return list.get(rowIndex).getProduct().getName();
            case 2: return list.get(rowIndex).getTotal(); 
        }
        return null;
    }
//</editor-fold>

}
